<%@ page 
import="org.apache.commons.httpclient.*
,org.apache.commons.httpclient.methods.*
,java.net.*
,java.util.ArrayList
,java.util.List
,javax.xml.parsers.SAXParser
,javax.xml.parsers.SAXParserFactory
,org.xml.sax.Attributes
,org.xml.sax.SAXException
,org.xml.sax.helpers.DefaultHandler
,javax.xml.parsers.ParserConfigurationException
,java.io.IOException
"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%!

public static String htmlEncode(String s){
    StringBuffer out = new StringBuffer();
    for(int i=0; i<s.length(); i++){
        char c = s.charAt(i);
        if(c > 127 || c=='"' || c=='<' || c=='>'){
           out.append("&#"+(int)c+";");
        }
        else{
            out.append(c);
        }
    }
    return out.toString();
}

public class FileItem {

	private boolean fileisfolder=true;
	private String filename="";
	private String filesizestring="";
	private long filesize=0;
	private String filetype="";

	public void setIsFolder(String newvalue){
		fileisfolder=newvalue==null || newvalue.equalsIgnoreCase("yes");
	}
	public boolean getIsFolder(){
		return fileisfolder;
	}
	public void setName(String newvalue){
		filename=newvalue;
	}
	public String getName(){
		return filename;
	}
	public void setType(String newvalue){
		//System.out.println("type="+newvalue);
		filetype=newvalue;
	}
	public String getType(){
		return filetype;
	}

	public void setSize(long size){
		filesize=size;
	}
	public long getSize(){
		return filesize;
	}
}


public class SAXParserFiles extends DefaultHandler {

	List<FileItem> myFiles;
	private String tempVal;
	private FileItem tempFile;
	private String url="";

	public SAXParserFiles(String url) {
		myFiles = new ArrayList<FileItem>();
		this.url=url;
		parseDocument();
	}

//	public void runExample() {
//		
//		printData();
//	}

	private void parseDocument() {
		SAXParserFactory spf = SAXParserFactory.newInstance();
		try {
			SAXParser sp = spf.newSAXParser();
			sp.parse(url, this);
		}catch(SAXException se) {
			se.printStackTrace();
		}catch(ParserConfigurationException pce) {
				pce.printStackTrace();
		}catch (IOException ie) {
			ie.printStackTrace();
		}		
	}

//	private void printData(){
//		System.out.println("\n\n\tNo of Files '" + myEmpls.size() + "'.\n");
//		Iterator it = myEmpls.iterator();
//		while(it.hasNext()) {
//			System.out.println("\n\t"+it.next().toString());
//		}
//	}

	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		tempVal = "";
		if(qName.equalsIgnoreCase("file")||qName.equalsIgnoreCase("networkResource")) {
			tempFile = new FileItem();
//			tempFile.setType(attributes.getValue("type"));
		}
	}

	public void characters(char[] ch, int start, int length)
			throws SAXException {
		tempVal = new String(ch, start, length);
	}

	public void endElement(String uri, String localName, String qName) throws SAXException {
		if(qName.equalsIgnoreCase("file")||qName.equalsIgnoreCase("networkResource")) {
			System.out.println("adding item");
			myFiles.add(tempFile);
		}
		else if (qName.equalsIgnoreCase("name")) {
			System.out.println("name="+tempVal);
			tempFile.setName(tempVal);
		}
		else if (qName.equalsIgnoreCase("isFolder")) {
			tempFile.setIsFolder(tempVal);
		}
		else if (qName.equalsIgnoreCase("type")) {
			tempFile.setType(tempVal);
		}
		else if (qName.equalsIgnoreCase("size")) {
			tempFile.setSize(Long.parseLong(tempVal));
		}
	}
}	
	
%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="jquery.min.js"></script>
<link rel="StyleSheet" href="popbox.css" type="text/css"/>

<script>
function selectAll(){
	 $("form#itemselections INPUT[@name='itemselect'][type='checkbox']").attr('checked', true);	
}
function selectNone(){
	 $("form#itemselections INPUT[@name='itemselect'][type='checkbox']").attr('checked', false);	
}
function submitSelected(){
	 $("form#itemselections INPUT[@name='itemselect'][type='checkbox']:checked").each(function (){
	queue($(this).val());
	$(this).attr('checked',false);
	 }
	 );	
	
	
}
</script>



</head>
<body class="content">


<%
String pophost = application.getInitParameter("pophost");
String thedavidport = application.getInitParameter("thedavidport");
String remoteport = application.getInitParameter("remoteport");
String mount=request.getParameter("mount");
//String dir=request.getParameter("dir");
//if (dir==null){
//	dir="";
//}

System.out.println("mount="+mount);
//System.out.println("dir.length="+mount.length());

String url = "http://" + pophost + ":" + thedavidport+"/network_browse?";
//String query = request.getQueryString();

//if (dir.length()>0){
//	url+="arg0=list_network_content&arg1="+mount+"&arg2="+dir;
if (mount.matches("[^\\/]+\\:\\/\\/.+\\/.+")){	
	url+="arg0=list_network_content&arg1="+mount+"&arg2=";
	url+="&arg3=&arg4=&arg5=&arg6=&arg7=true&arg8=true&arg9=true&arg10=";
}
else {
	url+="arg0=list_network_resource&arg1="+mount+"&arg2=";
	url+="&arg3=";
}

System.out.println("url="+url);
SAXParserFiles SPF=new SAXParserFiles(url);

//  crumb navigation
out.print("<form name=\"itemselections\" id=\"itemselections\">");

out.print("<table>");
out.print("<tr><td colspan='5'>&nbsp;");
String[] dirlist=mount.split("/");
String backdir="";
//out.print("[");
for (String thisdir :dirlist){

	if (backdir.length()==0){
		out.print(thisdir);
		backdir+=thisdir;
	}
	else {
		backdir+=thisdir;
		out.print("/<a href=\"javascript:browse(&quot;"+backdir+"&quot;);\">"+thisdir+"</a>");
	}
	backdir+="/";
}
out.print("&nbsp;</td></tr>");

out.print("<tr><td colspan='5'>");
%>
<button type="button" onclick="submitSelected();">ADD Selected</button>
<button type="button"  onclick="selectAll();submitSelected();">ADD All</button>
<button type="button"  onclick="selectAll();">Select All</button>
<button type="button"  onclick="selectNone();">Clear Selections</button>

<%
out.print("</td></tr>");
out.print("<tr><td colspan='5'><hr/></td></tr>");


// list items in directory

for (FileItem thisfile: SPF.myFiles){
	String name=thisfile.getName();
	String type=thisfile.getType();
	long size=(long)thisfile.getSize();
	double k=1024;
	String sz=(long)size+" b";
	
	//System.out.println("size:"+size);
	if ((long)size > (k*k*k*k)){
		//System.out.println("terrabyte range");
		sz=String.valueOf(Math.round((float)((double)size/(k*k*k*k)*10.0))/10.0)+" T";
	}
	else if ((long)size>(long)(k*k*k)){
		//System.out.println("gigabyte range");
		sz=String.valueOf(Math.round((float)((double)size/(k*k*k)*10.0))/10.0)+" G";
	}
	else if (size>k*k){
		//System.out.println("megabyte range");
		sz=String.valueOf(Math.round((float)((double)size/(k*k)*10.0))/10.0)+" M";
	}
	else if (size>k){
		//System.out.println("kilobyte range");
	
		sz=String.valueOf(Math.round((float)((double)size/(k)*10.0))/10.0)+" k";
	}

	
	boolean isFolder=thisfile.getIsFolder();
	out.print("<tr>");
	if (isFolder){
		out.print("<td>&nbsp;</td>");
		out.print("<td>&nbsp;</td>");
		String mountpoint=mount+"/"+name;
		%>
		<td class='icon'>
  	<img class="folder" coverpath="<%=mountpoint%>" src='folder.gif'/>
		</td>
		<%
//		out.print("<img alt='' src='folder.gif'>");
		out.print("<td class='title'><a href=\"javascript:browse(&quot;"+mount+"/"+name+"&quot;);\"> "+htmlEncode(name)+" </a></td>");
	}
	else {
		//data+="<td><button type='button' title='Add this to the Queue' onclick=\"queue(&quot;"+mount+"/"+dir+"/"+name+"&quot;);\" >Add</button></td>";
		out.print("<td class='action'><a href=\"javascript:queue(&quot;"+mount+"/"+name+"&quot;);\" title='Add this to the Queue'><img alt='ADD' src='plus.gif'></a></td>");
		
		if ("music".equalsIgnoreCase(type)||"video".equalsIgnoreCase(type)){
			%>
			<td><input type="checkbox" id="itemselect" name="itemselect" value="<%=mount+"/"+name%>"/></td> 
			<%
		}
		else {
			out.print("<td>&nbsp;</td>");
		}
		if ("photo".equalsIgnoreCase(type)){
			String rootpath=mount.replace("smb://POOHBEAR/","/popbox/");
			String httppath=mount.replace("smb://POOHBEAR/","/media/");
			String imgsize="30";
			String imageurl=httppath+"/"+name;
			%><td class='icon'>
			<img height="<%=imgsize %>" width="<%=imgsize%>" alt='(<%=type%>)' title='(<%=type%>)' src="<%=imageurl%>"/>
			</a>
			</td>
			<td class='title'>
			<a href="<%=imageurl%>" target="_blank"><%=htmlEncode(name)%></a>
			</td>
			<%
		}
		else {
			out.print("<td class='icon'><img alt='("+type+")' title='("+type+")' src='"+type+".gif'></td>");
			out.print("<td class='title'>"+htmlEncode(name)+" </td>");
	
		}
		
		out.print("<td class='size' title=\""+size+"\">("+sz+")</td>");
	}
	//alert(link);
	out.print("</tr>");
}
out.print("</table>");
out.print("</form>");

%>
<script>
function queue(filepath){
	parent.queue(filepath);
}

function browse(mount){
	window.location="?mount="+mount;
}

$(window).load(function () {
	 $(".photo").each(function (){
		var url="coverimg.jsp?mount="+$(this).attr("imagepath")+"&imgsize=30";	 
	 	var owner=$(this);
		$.ajax({
			type: "GET",
			url: url,
			dataType: "text",
			async: false,
			timeout: 500,
			//	crossDomain: 'true',
			success: function( data ) {
				//alert(data);

				var newimg=$(data).filter("img");
				
				//alert (newsrc);
				if (newimg){
					owner.attr("height",40);
					owner.attr("width",40);
					owner.attr("src",newimg.attr("src"));
				}
				
			}
		 
		})
	 
	 })
});

</script>


</body>
</html>
